package com.test.demo.util;

import cn.hutool.core.convert.Convert;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

@Slf4j
public class ExportUtil {


    /* 导出txt文件
     * @return
     */
    public static void exportTxtByPath(HttpServletResponse response, String cnName, InputStream inputStream) throws UnsupportedEncodingException {
        response.setCharacterEncoding("utf-8");
        //设置响应的内容类型
        response.setContentType("text/plain");
        //设置文件的名称和格式
        cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
        cnName = Convert.toStr(cnName, "JSON_FOR_UCC_");
        response.addHeader("Content-Disposition", "attachment;filename=" + cnName + ".txt");

        try (InputStream fis = new BufferedInputStream(inputStream);
             OutputStream out = new BufferedOutputStream(response.getOutputStream())) {
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            out.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("导出异常", e);
        }

    }

}
